<?php

namespace App\Http\Controllers\Admin;

use App\Services\MemberService;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Hash;

use Illuminate\Support\Facades\Cookie;

class UsersController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
//     public function index()
// {
//     // 检查cookie，过期了就要重新输入密码
//     $showUserPwdTime = Cookie::get('showUser');
//     if (!$showUserPwdTime) {
//         // 输入密码页面showUserPassword
//         return $this->showUserPassword();
//     }
//     if (time() - $showUserPwdTime > 7200) {
//         // 密码一小时过期
//         return $this->showUserPassword();
//     }
//     $levelMap = DB::table('user_level')->pluck('title', 'id');

//     // 查询用户游戏数据
//     $usersData = DB::table('users')
//         ->where(function ($query) {
//             if (!empty($_GET['search'])) {
//                 $query->orWhere('username', 'like', '%' . @$_GET['search'] . '%');
//                 $query->orWhere('mobile', 'like', '%' . @$_GET['search'] . '%');
//                 $query->orWhere('unionid', 'like', '%' . @$_GET['search'] . '%');
//             }
//             if (!empty($_GET['level_id'])) {
//                 $query->where('level_id', $_GET['level_id']);
//             }
//             if (!empty($_GET['birthday'])) {
//                 $query->where('birthday', $_GET['birthday']);
//             }
//         })
//         ->where(function ($query) {
//             if (!empty($_GET['last_login_time'])) {
//                 switch ($_GET['last_login_time']) {
//                     case 1:
//                         $query->where('game_login_time', '<=', date('Y-m-d H:i:s', strtotime('-15 day')))
//                             ->where('game_login_time', '>=', date('Y-m-d H:i:s', strtotime('-30 day')));
//                         break;
//                     case 2:
//                         $query->where('game_login_time', '<=', date('Y-m-d H:i:s', strtotime('-31 day')))
//                             ->where('game_login_time', '>=', date('Y-m-d H:i:s', strtotime('-60 day')));
//                         break;
//                     case 3:
//                         $query->where('game_login_time', '<=', date('Y-m-d H:i:s', strtotime('-60 day')));
//                         $query->orWhere('game_login_time', 'IS NULL');
//                 }
//             }
//         })
//         ->orderBy($_GET['sort'] ?? 'ly_balance', $_GET['order'] ?? 'desc')
//         ->paginate(15)
//         ->withPath(
//             '?search=' . @$_GET['search'] .
//             '&last_login_time=' . @$_GET['last_login_time'] .
//             '&level_id=' . @$_GET['level_id'] .
//             '&sort=' . ($_GET['sort'] ?? 'ly_balance') .
//             '&order=' . ($_GET['order'] ?? 'desc') .
//             '&birthday=' . @$_GET['birthday']
//         );

//     $kfMap = DB::table('customer_service')->pluck('nickname', 'id');
//     foreach ($usersData as &$item) {
//         $item->kf_name = '-';
//         $kf = DB::table('customer_service_user')->where('unionid', $item->unionid)->value('service_id');
//         if ($kf) {
//             $item->kf_name = $kfMap[$kf] ?? '-';
//         }
//     }

//     // 汇总数据
//     $totalLyBalance = DB::table('users')
//         ->where('ly_balance', '>', 1000)
//         ->sum('ly_balance') / 100;

//     $recent30DayLyBalance = DB::table('users')
//         ->where('game_login_time', '>=', date('Y-m-d H:i:s', strtotime('-30 days')))
//         ->where('ly_balance', '>', 1000)
//         ->sum('ly_balance') / 100;

//     $today = strtotime(date('Y-m-d'));
//     $todayStart = $today;
//     $todayEnd = $today + 86400 - 1;

//     $todayRechargeLyBalance = DB::table('user_balance_log')
//         ->where('create_time', '>=', $todayStart)
//         ->where('create_time', '<=', $todayEnd)
//         ->where('balance_type', 1)
//         ->where('from_type', 1)
//         ->sum('change') / 100;

//     $todayRealRechargeMoney = DB::table('user_balance_log')
//         ->join('user_recharge_order', 'user_balance_log.from_id', '=', 'user_recharge_order.id')
//         ->where('user_balance_log.create_time', '>=', $todayStart)
//         ->where('user_balance_log.create_time', '<=', $todayEnd)
//         ->where('user_balance_log.balance_type', 1)
//         ->where('user_balance_log.from_type', 1)
//         ->sum('user_recharge_order.money');

//     $todayExtraRechargeLyBalance = $todayRechargeLyBalance - $todayRealRechargeMoney;

//     $todayExchangeLyBalance = DB::table('user_balance_log')
//         ->where('create_time', '>=', $todayStart)
//         ->where('create_time', '<=', $todayEnd)
//         ->where('balance_type', 1)
//         ->where('from_type', 2)
//         ->sum('change') / 100;

//     return view('admin.users.index', [
//         'usersData' => $usersData,
//         'levelMap' => $levelMap,
//         'totalLyBalance' => $totalLyBalance,
//         'recent30DayLyBalance' => $recent30DayLyBalance,
//         'todayRechargeLyBalance' => $todayRechargeLyBalance,
//         'todayRealRechargeMoney' => $todayRealRechargeMoney,
//         'todayExtraRechargeLyBalance' => $todayExtraRechargeLyBalance,
//         'todayExchangeLyBalance' => $todayExchangeLyBalance
//     ]);
// }
    public function index(Request $request)
    {
        // 检查cookie，过期了就要重新输入密码
        $showUserPwdTime = Cookie::get('showUser');
        if (!$showUserPwdTime || time() - $showUserPwdTime > 7200) {
            // 密码两小时过期，重定向到密码输入页面
            return $this->showUserPassword();
        }

        $levelMap = DB::table('user_level')->pluck('title', 'id');

        // 查询用户游戏数据
        $usersData = DB::table('users')
            ->when($request->input('search'), function ($query, $search) {
                $query->where(function ($query) use ($search) {
                    $query->where('username', 'like', "%$search%")
                        ->orWhere('mobile', 'like', "%$search%")
                        ->orWhere('unionid', 'like', "%$search%");
                });
            })
            ->when($request->input('level_id'), function ($query, $level_id) {
                $query->where('level_id', $level_id);
            })
            ->when($request->input('birthday'), function ($query, $birthday) {
                $query->where('birthday', $birthday);
            })
            ->when($request->input('last_login_time'), function ($query, $last_login_time) {
                switch ($last_login_time) {
                    case 1:
                        $query->whereBetween('game_login_time', [
                            now()->subDays(30), now()->subDays(15)
                        ]);
                        break;
                    case 2:
                        $query->whereBetween('game_login_time', [
                            now()->subDays(60), now()->subDays(31)
                        ]);
                        break;
                    case 3:
                        $query->where('game_login_time', '<=', now()->subDays(60))
                            ->orWhereNull('game_login_time');
                }
            })
            ->orderBy($request->input('sort', 'ly_balance'), $request->input('order', 'desc'))
            ->paginate(15)
            ->appends($request->except('page'));

        $kfMap = DB::table('customer_service')->pluck('nickname', 'id');

        foreach ($usersData as &$item) {
            $item->kf_name = $kfMap[DB::table('customer_service_user')->where('unionid', $item->unionid)->value('service_id')] ?? '-';
        }

        // 汇总数据
        $totalLyBalance = DB::table('users')
                ->where('ly_balance', '>', 1000)
                ->sum('ly_balance') / 100;

        $recent30DayLyBalance = DB::table('users')
                ->where('game_login_time', '>=', now()->subDays(30))
                ->where('ly_balance', '>', 1000)
                ->sum('ly_balance') / 100;

        // $today = now()->startOfDay();
        // $todayEnd = now()->endOfDay();
        $today = strtotime(date('Y-m-d'));
        $todayStart = $today;
        $todayEnd = $today + 86400 - 1;

        $todayRechargeLyBalance = DB::table('user_balance_log')
                ->whereBetween('create_time', [$todayStart, $todayEnd])
                ->where('balance_type', 1)
                ->where('from_type', 1)
                ->sum('change') / 100;

        $todayRealRechargeMoney = DB::table('user_balance_log')
            ->join('user_recharge_order', 'user_balance_log.from_id', '=', 'user_recharge_order.id')
            ->whereBetween('user_balance_log.create_time', [$todayStart, $todayEnd])
            ->where('user_balance_log.balance_type', 1)
            ->where('user_balance_log.from_type', 1)
            ->sum('user_recharge_order.money');
        //     $todayRealRechargeMoney = DB::table('user_balance_log')
//         ->join('user_recharge_order', 'user_balance_log.from_id', '=', 'user_recharge_order.id')
//         ->where('user_balance_log.create_time', '>=', $todayStart)
//         ->where('user_balance_log.create_time', '<=', $todayEnd)
//         ->where('user_balance_log.balance_type', 1)
//         ->where('user_balance_log.from_type', 1)
//         ->sum('user_recharge_order.money');
        $todayExtraRechargeLyBalance = $todayRechargeLyBalance - $todayRealRechargeMoney;

        $todayExchangeLyBalance = DB::table('user_balance_log')
                ->whereBetween('create_time', [$todayStart, $todayEnd])
                ->where('balance_type', 1)
                ->where('from_type', 2)
                ->sum('change') / 100;

        // 用户积分统计
        $integralStats = DB::table('users')
            ->select(DB::raw("
            COUNT(CASE WHEN integral >= 50 THEN 1 END) as usersWithAtLeast50,
            COUNT(CASE WHEN integral >= 5000 THEN 1 END) as canDraw100Times,
            COUNT(CASE WHEN integral >= 2500 THEN 1 END) as canDraw50Times,
            COUNT(CASE WHEN integral >= 1000 THEN 1 END) as canDraw20Times,
            COUNT(CASE WHEN integral >= 500 THEN 1 END) as canDraw10Times
        "))
            ->first();

        return view('admin.users.index', [
            'usersData' => $usersData,
            'levelMap' => $levelMap,
            'totalLyBalance' => $totalLyBalance,
            'recent30DayLyBalance' => $recent30DayLyBalance,
            'todayRechargeLyBalance' => $todayRechargeLyBalance,
            'todayRealRechargeMoney' => $todayRealRechargeMoney,
            'todayExtraRechargeLyBalance' => $todayExtraRechargeLyBalance,
            'todayExchangeLyBalance' => $todayExchangeLyBalance,
            'integralStats' => $integralStats
        ]);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'username' => ['required', 'string', 'max:10', 'unique:users'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'max:16','confirmed'],
            'password_confirmation' => ['required','string','min:6'],
            'money' => ['required','numeric'],
            'birthday' => [],
        ]);

        //写入添加的用户
        DB::table('users')->insert([
            'username' => $request->username,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'money' => $request->money,
            'birthday' => $request->birthday ?? '1970-01-01',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        return response()->json(['message' => '添加成功。', 'success' => 'true']);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //查询游戏数据信息
        $userDataInfo = DB::table('users')
            ->select('id', 'username', 'email', 'password', 'money')
            ->where('id', $id)
            ->first();

        return view('admin.users.edit',[
            'userDataInfo'=>$userDataInfo
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        //验证表单
        $this->validate($request, [
            'password' => ['nullable', 'string', 'min:8', 'max:16','confirmed'],
            'password_confirmation' => ['nullable','string','min:8'],
            'money' => ['required','numeric'],
        ]);

        if($request->password){
            //更新游戏信息
            DB::table('users')
                ->where('id', $id)
                ->update([
                    'password' => Hash::make($request->password),
                    'money' => $request->money,
                ]);
        }else{
            //更新游戏信息
            DB::table('users')
                ->where('id', $id)
                ->update([
                    'money' => $request->money,
                ]);
        }

        return response()->json(['message' => '编辑成功。', 'success' => 'true']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        DB::table('users')
            ->whereIn('id', explode(',', $id))
            ->delete();

        return response()->json(['message' => '删除成功！', 'success' => 'true']);
    }

    // 输入密码页面
    public function showUserPassword()
    {
        return view('admin.users.user_password');
    }

    // 验证密码
    public function checkUserPassword(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'password' => ['nullable', 'string', 'min:2', 'max:16'],
        ]);
        $password = '123456';
        if($request->password != $password){
            return response()->json(['message' => '密码错误', 'success' => false]);
        }
        // 成功，写入一个cookie，为时间戳
        Cookie::queue('showUser', time());
        return response()->json(['message' => '', 'success' => 'true']);
    }

    // 修改余额
    public function showSetBalance($uid)
    {
        $userInfo = DB::table('users')->find($uid);
        return view('admin.users.edit_balance', ['userDataInfo' => $userInfo]);
    }

    /**
     * 修改余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setBalance(Request $request)
    {
        if(!isSuperAdmin()) {
            return errorResp('非管理员不可修改');
        }
        $this->validate($request, [
            'tp' => ['required', 'string'],
            'balance' => ['required'],
            'id' => ['required', 'int'],
        ]);
        $userInfo = DB::table('users')->find($request->id);
        if (!$userInfo) {
            return errorResp('用户错误');
        }
        if ($request->tp == 'mobile') {
            $res = DB::table('users')->where('id', $userInfo->id)
                ->update([
                    'mobile'=>$request->balance,
                ]);
            if ($res) {
                return successResp('');
            }
            return errorResp('修改失败');
        }
        if ($request->tp == 'birthday') {
            $res = DB::table('users')->where('id', $userInfo->id)
                ->update([
                    'birthday'=>$request->balance,
                ]);
            if ($res) {
                return successResp('');
            }
            return errorResp('修改失败');
        }
        $change = (int)$request->balance - $userInfo->integral;
        $bt = MemberService::BalanceTypeJf;
        if ($request->tp == 'ly') {
            $bt = MemberService::BalanceTypeLy;
            $change = (int)$request->balance - $userInfo->ly_balance;
        }
        if ($request->tp == 'wf') {
            $bt = MemberService::BalanceTypeWf;
            $change = (int)$request->balance - $userInfo->wf_integral;
        }
        if ($request->tp == 'red') {
            $bt = MemberService::BalanceTypered;
            $change = (int)$request->balance - $userInfo->red_packet_coin;
        }
        if ($request->tp == 'newRedPacketCoin') {
            $bt = MemberService::NewRedPacketCoin;
            $change = (int)$request->balance - $userInfo->new_red_packet_coin;
        }
        MemberService::setMemberBalance(
            $userInfo,
            $bt,
            MemberService::FromTypeAdmin,
            0,
            $change,
            '管理员手动修改'
        );
        return successResp('');
    }

    public function showBalanceLog()
    {
        return view('admin.users.balance_log');
    }

    public function showVersionLog()
    {
        return view('admin.users.version_log');
    }

    /**
     * 获取余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBalanceLog(Request $request)
    {
        if(@$_GET['game_account']){
            $list = DB::table('draw_log')
                ->where('game_num', $_GET['game_account'])
                ->where('draw_id', 0)
                ->where('is_luck', 1)
                ->orderBy('id', 'desc')
                ->paginate(10);
            foreach ($list as $v) {
                $balanceLog = DB::table('user_balance_log')
                    ->where(function ($query) {
                        if (@$_GET['unionid']) {
                            $query->where('unionid', @$_GET['unionid']);
                        }
                        // if (@$_GET['balance_type']) {
                        //     $query->where('balance_type', @$_GET['balance_type']);
                        // }
                        // if (@$_GET['from_type']) {
                        //     $query->where('from_type', @$_GET['from_type']);
                        // }

                        // if (@$_GET['remark']) {
                        //     $query->where('remark', 'like', '%'.@$_GET['remark'].'%');
                        // }
                        // if (@$_GET['start_time']) {
                        //     $query->where('create_time', '>=', strtotime(@$_GET['start_time'].' 00:00:00'));
                        // }
                        // if (@$_GET['end_time']) {
                        //     $query->where('create_time', '<=', strtotime(@$_GET['end_time'].' 23:59:59'));
                        // }
                    })
                    ->where('from_id', $v->id)
                    ->first();
                if($balanceLog){
                    $v->account = $_GET['game_account'];
                    $v->create_time = date('Y-m-d H:i:s', $balanceLog->create_time) ;
                    $v->remark = $balanceLog->remark;
                    $v->unionid = $balanceLog->unionid;
                    $v->balance_type = $balanceLog->balance_type;
                    $v->origin = $balanceLog->origin;
                    $v->now = $balanceLog->now;
                    $v->change = $balanceLog->change;
                    $v->from_type = $balanceLog->from_type;
                }
            }
        }else{
            $list = DB::table('user_balance_log')
                ->where(function ($query) {
                    if (@$_GET['unionid']) {
                        $query->where('unionid', @$_GET['unionid']);
                    }
                    if (@$_GET['balance_type']) {
                        $query->where('balance_type', @$_GET['balance_type']);
                    }
                    if (@$_GET['from_type']) {
                        $query->where('from_type', @$_GET['from_type']);
                    }

                    if (@$_GET['remark']) {
                        $query->where('remark', 'like', '%'.@$_GET['remark'].'%');
                    }
                    if (@$_GET['start_time']) {
                        $query->where('create_time', '>=', strtotime(@$_GET['start_time'].' 00:00:00'));
                    }
                    if (@$_GET['end_time']) {
                        $query->where('create_time', '<=', strtotime(@$_GET['end_time'].' 23:59:59'));
                    }
                })
                ->orderBy('id', 'desc')
                ->paginate(10);
            foreach ($list as $v) {
                $v->create_time = date('Y-m-d H:i:s', $v->create_time);

                $v->site_host = '-';
                $v->account = '-'; // 默认值
                if ($v->from_type == 2 || $v->from_type == 13) {
                    $drawLog = DB::table('draw_log')
                        ->where('id', $v->from_id)
                        ->where(function ($query) {
                            $query->where('draw_id', 0)
                                ->orWhere('draw_id', 20);
                        })
                        ->where('is_luck', 1)
                        ->first();
                    if ($drawLog) {
                        $v->account = $drawLog->game_num;
                        $v->site_host = $drawLog->source_url;
                    }
                }
                // 获取 site_host
                if ($v->from_type == MemberService::FromTypeRecharge) {
                    $recharge = DB::table('user_recharge_order')->find($v->from_id);
                    if ($recharge) {
                        $v->site_host = $recharge->site_host;
                    }
                }
            }
        }
        return successResp($list);
    }


    /**
     * 余额统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBalanceLogStatistic(Request $request)
    {
        $change = DB::table('user_balance_log')
            ->where(function ($query) {
                if (@$_GET['unionid']) {
                    $query->where('unionid', @$_GET['unionid']);
                }
                if (@$_GET['balance_type']) {
                    $query->where('balance_type', @$_GET['balance_type']);
                }
                if (@$_GET['from_type']) {
                    $query->where('from_type', @$_GET['from_type']);
                }
                if (@$_GET['remark']) {
                    $query->where('remark', 'like', '%'.@$_GET['remark'].'%');
                }
                if (@$_GET['start_time']) {
                    $query->where('create_time', '>=', strtotime(@$_GET['start_time'].' 00:00:00'));
                }
                if (@$_GET['end_time']) {
                    $query->where('create_time', '<=', strtotime(@$_GET['end_time'].' 23:59:59'));
                }
            })
            ->sum('change');
        return successResp(['change' => $change]);
    }

    public function getInviteeUser(Request $request)
    {
        $this->validate($request, [
            'id' => ['required', 'int'],
        ]);
        $userList = DB::table('users')->where('from_id', $request->id)->orderBy('id', 'desc')->get();
        return view('admin.users.invitee_list', ['userList' => $userList]);
    }

    /**
     * 生日礼物待送列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBirthdayGiftList(Request $request)
    {
        $curYear = date('Y');
        $list = DB::table('users')
            ->selectRaw("*, TIMESTAMPDIFF(DAY, CONCAT('{$curYear}-',LPAD(MONTH(`birthday`), 2, '0'), '-', LPAD(DAY(`birthday`), 2, '0')), `last_birthday_gift_time`) AS days_diff")
            ->where(function ($query) {
                if (@$_GET['unionid']) {
                    $query->where('unionid', @$_GET['unionid']);
                }
            })
            ->whereNotNull('birthday')
            ->having('days_diff','<=', -365)
            ->where('level_id','>=', 10)
            ->orderBy('days_diff', 'asc')
            ->paginate(10);
        foreach ($list as $v) {
            // $v->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return successResp($list);
    }

    public function showBirthdayList()
    {
        return view('admin.users.birthday');
    }

    public function showWaitFestival()
    {
        return view('admin.users.wait_festival');
    }

    public function showGiftList()
    {
        return view('admin.users.gift_list');
    }

    /**
     * 送礼列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGiftList(Request $request)
    {
        $festival = MemberService::getFestival();
        $list = DB::table('user_gift_log')
            ->where(function ($query) {
                if (@$_GET['unionid']) {
                    $query->where('unionid', @$_GET['unionid']);
                }
                if (@$_GET['gift_type']) {
                    $query->where('gift_type', @$_GET['gift_type']);
                }
                if (@$_GET['festival_id']) {
                    $query->where('festival_id', @$_GET['festival_id']);
                }
            })
            ->orderBy('id','desc')
            ->paginate(10);
        foreach ($list as &$v) {
            $v->festival_name = $festival[$v->festival_id] ?? '-';
        }
        return successResp($list);
    }

    /**
     * 送礼
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function sendGift(Request $request)
    {
        $this->validate($request, [
            'unionid' => ['required', 'string'],
            'gift_type' => ['required'],
            'festival_id' => [],
        ]);
        $tx = DB::table('user_gift_log')->where('unionid', $request->unionid)
            ->where('gift_type', $request->gift_type);
        if ($request->festival_id) {
            $tx = $tx->where('festival_id', $request->festival_id);
        }
        $sendLog = $tx->value('create_time');
        if ($sendLog) {
            $lastDate = new \DateTime($sendLog);
            $now = new \DateTime();
            $days = $now->diff($lastDate)->format('%a');
            if ((int)$days < 300) {
                return errorResp('距离上次送礼时间小于300天');
            }
        }
        DB::table('user_gift_log')->insert([
            'unionid' => $request->unionid,
            'gift_type' => $request->gift_type,
            'festival_id' => $request->festival_id,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        if ($request->gift_type == 1) {
            DB::table('users')->where('unionid', $request->unionid)->update(['last_birthday_gift_time'=>date('Y-m-d')]);
        }
        return successResp('发放成功');
    }

    /**
     * 获取待送礼列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getWaitFestivalList(Request $request)
    {
        $festivalId = $request->get('festival_id', 0);
        if ($festivalId <= 0) {
            return errorResp('请选择节日');
        }
        $list = DB::table('users')
            ->where('level_id', '>', 10)
            ->whereNotIn("unionid", function ($query) use($festivalId) {
                $query->select('unionid')
                    ->from('user_gift_log')
                    ->where('festival_id', $festivalId)
                    ->where('create_time', '>', date('Y-01-01'));
            })
            ->paginate(10);
        $unionIds = [];
        foreach ($list as $item) {
            $unionIds[] = $item->unionid;
        }
        $sendLog = DB::table('user_gift_log')->whereIn('unionid', $unionIds)
            ->where('gift_type', 2)
            ->where('festival_id', $festivalId)
            ->orderBy('id','desc')
            ->pluck('create_time', 'unionid');
        foreach ($list as &$item) {
            $item->last_time = $sendLog[$item->unionid] ?? '-';
        }
        return successResp($list);
    }

    public function getFestival()
    {
        $list = MemberService::getFestival();
        return successResp($list);
    }
}
